#!/usr/bin/env bash

exec 2>&1

set -e

# Make a copy of the distribution for syncing, and inject all the configs.
TEMP_DIST_PATH="{{ pkg.svc_var_path }}/dist"
rm -rf $TEMP_DIST_PATH
mkdir -p $TEMP_DIST_PATH
cp -R {{ pkg.path }}/dist/* $TEMP_DIST_PATH

# Replace base assets path in static references
find $TEMP_DIST_PATH -type f -name *.html -exec sed -i "s/$(echo "base_assets_path" | sha256sum | cut -d' ' -f1)\//{{ strReplace cfg.general.base_assets_path "/" "\\/" }}/g" {} \;
find $TEMP_DIST_PATH -type f -name *.css -exec sed -i "s/$(echo "base_assets_path" | sha256sum | cut -d' ' -f1)\//{{ strReplace cfg.general.base_assets_path "/" "\\/" }}/g" {} \;

# Inject window.env by splitting file on expected BUILD_CONFIGS line
cd $TEMP_DIST_PATH/pages

for f in *.html
do
  csplit $f /META_TAGS/ > /dev/null
  cat xx00 > $f

{{#each cfg.general ~}}
  echo "<meta name=\"env:{{ @key }}\" content=\"{{ this }}\"/>" >> $f
{{/each}}

  cat xx01 >> $f
  rm xx00
  rm xx01
done

cd -

if [[ "{{ cfg.deploy.type }}" == "s3" ]] ;
then
  # need to upload wasm blobs with wasm content type explicitly because, unlike all
  # other assets, AWS's built-in MIME type dictionary doesn't know about that one

  AWSCLI={{ pkgPathFor "core/aws-cli" }}/bin/aws

  $AWSCLI s3 sync --region {{ cfg.deploy.region }} --acl public-read --cache-control "public, max-age=31536000" --include "*" --exclude "*.wasm" "$TEMP_DIST_PATH/assets" "s3://{{ cfg.deploy.target }}/hubs/assets"
  $AWSCLI s3 sync --region {{ cfg.deploy.region }} --acl public-read --cache-control "public, max-age=31536000" --exclude "*" --include "*.wasm" --content-type "application/wasm" "$TEMP_DIST_PATH/assets" "s3://{{ cfg.deploy.target }}/hubs/assets"
  
  $AWSCLI s3 sync --region {{ cfg.deploy.region }} --acl public-read --cache-control "no-cache" --delete "$TEMP_DIST_PATH/pages" "s3://{{ cfg.deploy.target }}/hubs/pages/latest"
  $AWSCLI s3 sync --region {{ cfg.deploy.region }} --acl public-read --cache-control "no-cache" --delete "$TEMP_DIST_PATH/pages" "s3://{{ cfg.deploy.target }}/hubs/pages/releases/{{ pkg.version }}.{{ pkg.release }}"
fi

if [[ "{{ cfg.deploy.type }}" == "cp" ]] ;
then
  mkdir -p "{{ cfg.deploy.target }}/hubs/pages/releases"
  mkdir -p "{{ cfg.deploy.target }}/hubs/pages/latest"

  cp -R "$TEMP_DIST_PATH/assets" "{{ cfg.deploy.target }}/hubs"
  cp -R $TEMP_DIST_PATH/pages/* "{{ cfg.deploy.target }}/hubs/pages/latest"
  cp -R "{{ cfg.deploy.target }}/hubs/pages/latest" "{{ cfg.deploy.target }}/hubs/pages/releases/{{ pkg.version }}.{{ pkg.release }}"
fi

exec sleep 999999999999
